﻿/*
The MIT License

Copyright (c) 2009 Gil Beyruth

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/


application.roomSO    = null; 
pendingUpdate = null;
//LISTA USUARIOS
function listCurrentUsers(){
	trace("-------------- Current Users --------------");
	var i, user;
	var total = application.clients.length;
	trace("There are " + total + " current users.");
	for (i = 0; i < total; i++){
		user = application.clients[i];
		trace(user.getConnectionInfo());
	}
	trace("-------------------------------------------");
}
/**
 * This is not called when this instance changes the shared object.
 **/
function RoomList_onSync(list){
    trace ("roomSO.onSync> Here is what is in the roomList:");
   var names = application.roomSO.getPropertyNames();
   for (var i in names){
	   var propVal = application.roomSO.getProperty(names[i]);
      trace(" Total users on >" + names[i] +":"+propVal.length); 
	 	for(var j in propVal){
		trace("     roomSO["+names[i]+"].onSync>" + j +" username:"+propVal[j].un +" uid:"+propVal[j].uid);
	 
		}
   } 
}


application.onAppStart = function(){
   var aName = application.name;
   trace("onAppStart> application name: " + aName);
	this.clientCount = 0;
	this.userSO = SharedObject.get("userSO", false);		
	this.chatSO = SharedObject.get("chatSO", false);
	this.roomSO = SharedObject.get("roomSO", false);
	this.roomSO.onSync = RoomList_onSync;
   	trace("onAppStart> roomSO: " + this.roomSO); 

	this.gameSO = SharedObject.get("gameSO", false);

	this.clientList = [];
	this.uid = 1;


	//USUARIO TIME
	Client.prototype.getTimeConnected = function() {
		var now = new Date().getTime();
		return (now - this.connectTime)/1000; // seconds
	}
	//USUARIO PING
	Client.prototype.getPingTime = function(){
		if (this.ping()){
			if(this > 20000)application.disconnect(this, {msg : "Low bandwidth. Ping to high. Disconnected."});
			return this.getStats().ping_rtt / 2;
		}
		else{
			application.disconnect(this, {msg : "Low bandwidth. Ping to high. Disconnected."});
			return "Cliente não conectado."
		}
		
	}
	
	//USUARIO CONNECTION
	Client.prototype.getConnectionInfo = function() {
		if(this.username==undefined)this.username="SERVER";
		if(this.uid==undefined)this.uid="0";
	  		return 	"  IP: "              	+ this.ip +
					", user name: "       	+ this.username +
					", uid: "      			+ this.uid +
					", id: "      			+ this.id +
					", connection time: " 	+ this.getTimeConnected() +
					", ping time: "       	+ this.getPingTime();
	}
	//USUARIO NAME
	Client.prototype.getUserName = function(){
		return client.username;
	}
	
	Client.prototype.checkBandwidth = function() 
	{
		application.calculateClientBw(this);
	}

	 var aName = application.name;
	   if (aName != 'lobby_rooms/lobby'){
		  badInstance = true;
		  trace("onAppStart> Bad instance: " + aName);
		  return;
	   }  
	
	setInterval(listCurrentUsers, 60000);
   
}

application.calculateClientBw = function(client)
{
	var res = new Object();
	res.latency = 0;
	res.cumLatency = 1;
	res.bwTime = 0;
	res.count = 0;
	res.sent = 0;
	res.client = client;
	var stats = client.getStats();
	var now = (new Date()).getTime()/1;
	res.pakSent = new Array();
	res.pakRecv = new Array();
	res.beginningValues = {b_down:stats.bytes_out, b_up:stats.bytes_in, time:now};
	res.onResult = function(p_val) {

		var now = (new Date()).getTime()/1;
		this.pakRecv[this.count] = now;
		trace("** onResult this.count = " + this.count + " : this.sent " + this.sent);
		this.count++;
		var timePassed = (now - this.beginningValues.time);

		if (this.count == 1) {
			this.latency = Math.min(timePassed, 800);
			this.latency = Math.max(this.latency, 10);
		}
		if ( this.count == 2 && (timePassed<2000))
		{
			this.pakSent[res.sent++] = now;
			this.cumLatency++;
			this.client.call("onBWCheck", res, application.payload);
		}
		else if ( this.sent == this.count )
		{	
			// See if we need to normalize latency
			if ( this.latency >= 100 )
			{ // make sure we detect sattelite and modem correctly
				if (  this.pakRecv[1] - this.pakRecv[0] > 1000 )
				{
					this.latency = 100;
				}
			}

			// Got back responses for all the packets compute the bandwidth.
			var stats = this.client.getStats();
			var deltaDown = (stats.bytes_out - this.beginningValues.b_down)*8/1000;
			var deltaTime = ((now - this.beginningValues.time) - (this.latency * this.cumLatency) )/1000;
			if ( deltaTime <= 0 )
				deltaTime = (now - this.beginningValues.time)/1000;
			
			var kbitDown = Math.round(deltaDown/deltaTime);

			trace("onBWDone: kbitDown = " + kbitDown + ", deltaDown= " + deltaDown + ", deltaTime = " + deltaTime + ", latency = " + this.latency + "KBytes " + (stats.bytes_out - this.beginningValues.b_down)/1024) ;

			this.client.call("onBWDone", null, kbitDown,  deltaDown, deltaTime, this.latency );
		}
	}
	res.pakSent[res.sent++] = now;
	client.call("onBWCheck", res, "");
	res.pakSent[res.sent++] = now;
	client.call("onBWCheck", res, application.payload);

}

application.onConnect = function( client, room, userName,  password , userStatus)
{
	client.connectTime = new Date().getTime();
	trace("onConnect> client: " + client + " room: " + room + " application.name: " + application.name);
	application.acceptConnection(client);
	
	if (room != undefined &&  room != "lobby" && client.ip == '127.0.0.1'){ 
		
		trace("A room has connected named: " + room + " at IP: " + client.ip);
	
	}else{
		client.swf = true;  // remember this client is a swf not a room.
		trace("Client connected. Assigning uid:  " + this.uid + ". Username: " + userName + ". Password: " + password+ ". userStatus: "+userStatus);
		client.uid = this.uid;
		client.username = userName;
		client.userStatus = userStatus;
		client.room = room;
		// store this client for later retrieval
		this.clientList.push({un:userName,r:room,uid: this.uid,us:userStatus});
		trace(this.clientList[0].un)	
		this.userSO.setProperty(client.uid, client);
	
		var msg = "<font color='#666666'><b>*** " + client.username + " joined ***</b></font><br>";
		this.chatSO.send("onMsgSend", msg);

		client.call("onUserid", null, client.uid);
		trace("CALL FUNCTION callFromServer :"+ client.uid)
		
		// increase uid ready for next user
		this.uid++;
		this.clientCount++; 
		
		if ( this.roomSO ){
			trace("setClientList on LOBBY")
			this.roomSO.setProperty('lobby', this.clientList );
		}
		else{
			trace("onConnect> Room list is not available yet! - never happens!\n")
		}       
		trace("A client has connected from: " + client.ip + ". There are now: " + this.clientCount + " client(s).");
	}
   	
		
}

application.onDisconnect = function(client){
   if (client.swf){  // it is a client and not a room instance...
	 if(this.clientList[0]){
		 for(var i=0;i< this.clientList.length;i++){
			if(this.clientList[i].uid==client.uid){
				userRemoved = this.clientList.splice(i,i+1);
				trace("removed user:" +userRemoved[0].un);
			}
			if(this.clientList[i])trace("Users on the room : " +this.clientList[i].un)
		}
		if(this.clientList)this.clientList.sort();
		
       if (this.roomSO){
          this.roomSO.setProperty('lobby', this.clientList  );
       }
      
	 }else{
		trace("empty clientList") 
	}
	 this.clientCount--;
	 
	trace("Client disconnected. UID:  " +client.uid);
	
	var msg = "<font color='#666666'><b>*** " + client.username + " has left ***</b></font><br>";
	this.chatSO.send("onMsgSend", msg);
	this.userSO.setProperty(client.uid, null);
	 trace("A client has disconnected. There are now: " + this.clientCount + " client(s).");
   }
}

application.onAppStop = function(){
   // Do nothing for now...
   this.clientList = undefined;
   this.roomSO.setProperty('lobby', null);
}


Client.prototype.getPageUrl = function() {
	return this.pageUrl;
}

Client.prototype.getReferrer = function() {
	return this.referrer;
}

String.prototype.trim = function () {
	
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

